package com.yonyou.ypd.bizflow.utils;

import com.alibaba.fastjson.JSONObject;
import com.yonyou.iuap.context.InvocationInfoProxy;
import com.yonyou.iuap.yms.http.*;
import com.yonyou.iuap.yms.http.exception.YmsHttpException;
import com.yonyoucloud.iuap.ucf.mdd.starter.ucg.openapi.isv.router.module.isvrequest.ISVRequest;
import com.yonyoucloud.iuap.ucf.mdd.starter.ucg.openapi.isv.router.module.isvrequest.ISVRequestBody;
import io.netty.handler.ssl.SslContext;
import io.netty.handler.ssl.SslContextBuilder;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.client.utils.URIBuilder;
import org.springframework.beans.factory.annotation.Autowired;

import javax.net.ssl.SSLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 通讯https工具类
 *
 * @author lizhgb
 * @date 2015-9-6l
 * <p>
 * 底层基于ymsHttpClient进行改造，对外接口不变 2024-2-19
 */
@Slf4j
public class IsvHttpClientUtil extends HttpClientUtil{

    private static final String DEFAULT_CONTENT_TYPE_FORM = "application/x-www-form-urlencoded";
    private static final String DEFAULT_CONTENT_TYPE_JSON = "application/json;charset=utf-8";
    private static final String CONTENT_TYPE_NAME = "Content-Type";
    private static final int MAX_TIMEOUT = 30_000;
    private static final int SOCKET_TIMEOUT = 5_000;

    private final YmsHttpClient httpclient = createHttpClient();

    @Autowired
    private ISVRequest isvRequest;

    private synchronized YmsHttpClient createHttpClient() {

        YmsHttpConfig config = new YmsHttpConfig();
        config.setSocketTimeout(SOCKET_TIMEOUT).setConnectTimeout(MAX_TIMEOUT).setConnectionRequestTimeout(MAX_TIMEOUT);
        SslContext context;
        try {
            context = SslContextBuilder.forClient().build();
        } catch (SSLException e) {
            throw new RuntimeException(e);
        }
        config.setSslContext(context);
        return new YmsHttpClient(config);

    }

    /**
     * 发送https post请求
     *
     * @param action
     * @param bodyParam
     * @return
     * @throws Exception
     * @author lizhgb
     * @Date 2015-9-10 上午11:12:55
     */
    public  String httpsPost(String action, Object bodyParam) throws Exception {
        return httpsPost(action, null, bodyParam);
    }


    /**
     * 发送https post请求
     *
     * @param url
     * @param bodyParam
     * @return
     * @throws Exception
     */
    public  String httpsPostForm(String url, List<NameValuePair> bodyParam) throws Exception {
        return httpsPostForm(url, null, bodyParam);
    }


    /**
     * 发送https post请求
     *
     * @param url
     * @return
     * @throws Exception
     * @author lizhgb
     * @Date 2015-9-6 下午1:32:06
     */
    public  String httpsPostForm(String url, Map<String, String> headerParams, List<NameValuePair> bodyParams) throws Exception {
        LogUtil.debug("Post请求地址：" + url);
        if (InvocationInfoProxy.getYhtAccessToken()!=null && !InvocationInfoProxy.getYhtAccessToken().startsWith("btt")) {
            ISVRequestBody isvRequestBody = new ISVRequestBody();
            isvRequestBody.setUrl(url);
            isvRequestBody.setRequestMethod("POSTJSON");
            HashMap<String, String> hashMap = new HashMap<>();
            hashMap.put("data", JSONObject.toJSONString(bodyParams));
            isvRequestBody.setParams(hashMap);
            String yhtAccessToken = InvocationInfoProxy.getYhtAccessToken();
            if(headerParams == null) {
                headerParams = new HashMap<>();
            }
            headerParams.put("yht_access_token", yhtAccessToken);
            isvRequestBody.setHeaders(headerParams);
            String result = isvRequest.doRequest(InvocationInfoProxy.getTenantid(), isvRequestBody);
            return result;
        }

        YmsHttpRequestBuilder build = new YmsHttpRequestBuilder().url(url).method(YmsHttpMethod.POST);

        //header参数
        build.addHeader(CONTENT_TYPE_NAME, DEFAULT_CONTENT_TYPE_FORM);
        if (headerParams != null && headerParams.size() > 0) {
            LogUtil.debug("Post请求Header：" + JsonUtil.toJSONString(headerParams));
            for (Map.Entry<String, String> entry : headerParams.entrySet()) {
                build.addHeader(entry.getKey(), entry.getValue());
            }
        }

        //entity数据
        if (bodyParams != null) {
            LogUtil.debug("Post请求Body：" + JsonUtil.toJSONString(bodyParams));
            for (NameValuePair nameValuePair : bodyParams) {
                String cleanName = StringUtil.htmlEscape(nameValuePair.getName());
                String cleanValue = StringUtil.htmlEscape(nameValuePair.getValue());
                build.addFormParam(cleanName, cleanValue);
            }
        }

        String resultStr = null;
        try (YmsHttpResponse ymsHttpResponse = httpclient.execute(build.build())) {
            resultStr = ymsHttpResponse.getBodyString();
            int statusCode = ymsHttpResponse.getStatusCode();
            if (statusCode != HttpStatus.SC_OK) {
                throw new Exception(getHttpInfoStr(statusCode, url, headerParams, bodyParams, resultStr));
            }
        } catch (YmsHttpException e) {
            throw new Exception(getHttpInfoStr(null, url, headerParams, bodyParams, resultStr));
        }

        LogUtil.debug("Post请求返回：" + resultStr);
        return StringUtil.cleanXSS(resultStr);
    }

    /**
     * 发送https post请求
     *
     * @param action
     * @return
     * @throws Exception
     * @author lizhgb
     * @Date 2015-9-6 下午1:32:06
     */
    public  String httpsPost(String action, Map<String, String> headerParams, Object bodyParams) throws Exception {
        String url = action;
        LogUtil.debug("Post请求地址：" + url);

        if (InvocationInfoProxy.getYhtAccessToken()!=null && !InvocationInfoProxy.getYhtAccessToken().startsWith("btt")) {
            ISVRequestBody isvRequestBody = new ISVRequestBody();
            isvRequestBody.setUrl(url);
            isvRequestBody.setRequestMethod("POSTJSON");
            HashMap<String, String> hashMap = new HashMap<>();
            hashMap.put("data", JSONObject.toJSONString(bodyParams));
            isvRequestBody.setParams(hashMap);
            String yhtAccessToken = InvocationInfoProxy.getYhtAccessToken();
            if(headerParams == null) {
                headerParams = new HashMap<>();
            }
            headerParams.put("yht_access_token", yhtAccessToken);
            isvRequestBody.setHeaders(headerParams);
            String result = isvRequest.doRequest(InvocationInfoProxy.getTenantid(), isvRequestBody);
            return result;
        }

        YmsHttpRequestBuilder build = new YmsHttpRequestBuilder().url(url).method(YmsHttpMethod.POST);

        //header参数
        build.addHeader(CONTENT_TYPE_NAME, DEFAULT_CONTENT_TYPE_JSON);
        if (headerParams != null && headerParams.size() > 0) {
            LogUtil.debug("Post请求Header：" + JsonUtil.toJSONString(headerParams));
            for (Map.Entry<String, String> entry : headerParams.entrySet()) {
                build.addHeader(entry.getKey(), entry.getValue());
            }
        }

        //body参数
        if (bodyParams != null) {
            build.body(JsonUtil.toJSONString(bodyParams));
        }

        String resultStr = null;
        try (YmsHttpResponse ymsHttpResponse = httpclient.execute(build.build())) {
            resultStr = ymsHttpResponse.getBodyString();
            int statusCode = ymsHttpResponse.getStatusCode();
            if (statusCode != HttpStatus.SC_OK) {
                throw new Exception(getHttpInfoStr(statusCode, url, headerParams, bodyParams, resultStr));
            }
        } catch (YmsHttpException e) {
            throw new Exception(getHttpInfoStr(null, url, headerParams, bodyParams, resultStr), e);
        }

        LogUtil.debug("Post请求返回：" + resultStr);
        return StringUtil.cleanXSS(resultStr);
    }

    public  String getHttpInfoStr(Object statusCode, String url, Map<String, String> headerParam, Object bodyParams, String resultStr, Throwable t) {
        String s1 = "[请求异常]:status:" + statusCode + ", result:" + resultStr;
        if (t != null && t.getCause() != null) {
            s1 += ", Caused by:" + t.getCause().getLocalizedMessage();
        }
        s1 += ", url:" + url + ", header:" + JsonUtil.toJSONString(headerParam) + ", body:" + JsonUtil.toJSONString(bodyParams);
        return s1;
    }

    public  String getHttpInfoStr(Object statusCode, String url, Map<String, String> headerParam, Object bodyParams, String resultStr) {
        return getHttpInfoStr(statusCode, url, headerParam, bodyParams, resultStr, null);
    }

    public  String getHttpInfoStr(String url, Map<String, String> headerParam, Object bodyParams, String resultStr) {
        return getHttpInfoStr(null, url, headerParam, bodyParams, resultStr, null);
    }

    /**
     * 发送https get请求
     *
     * @param url
     * @return
     * @throws Exception
     * @author lizhgb
     * @Date 2015-9-7 上午9:06:57
     */
    public  String httpsGet(String url, Map<String, String> headerParams, List<NameValuePair> bodyParams) throws Exception {

        URIBuilder uriBuilder = new URIBuilder();
        if (bodyParams != null && !bodyParams.isEmpty()) {
            for (NameValuePair pair : bodyParams) {
                uriBuilder.setParameter(pair.getName(), pair.getValue());
            }
        }
        String urlWithParam = url + uriBuilder;
        LogUtil.debug("Get请求地址：" + urlWithParam);

        if (InvocationInfoProxy.getYhtAccessToken()!=null && !InvocationInfoProxy.getYhtAccessToken().startsWith("btt")) {
            ISVRequestBody isvRequestBody = new ISVRequestBody();
            isvRequestBody.setUrl(urlWithParam);
            isvRequestBody.setRequestMethod("GET");
            HashMap<String, String> paramsMap = new HashMap<>();
            isvRequestBody.setParams(null);
            String yhtAccessToken = InvocationInfoProxy.getYhtAccessToken();
            if(headerParams == null) {
                headerParams = new HashMap<>();
            }
            headerParams.put("yht_access_token", yhtAccessToken);
            isvRequestBody.setHeaders(headerParams);
            String result = isvRequest.doRequest(InvocationInfoProxy.getTenantid(), isvRequestBody);
            return result;
        }

        YmsHttpRequestBuilder build = new YmsHttpRequestBuilder().url(urlWithParam).method(YmsHttpMethod.GET);

        LogUtil.debug("Get请求Header：" + JsonUtil.toJSONString(headerParams));
        if (headerParams != null && !headerParams.isEmpty()) {
            for (Map.Entry<String, String> entry : headerParams.entrySet()) {
                build.addHeader(entry.getKey(), entry.getValue());
            }
        }

        String resultStr = null;
        try (YmsHttpResponse ymsHttpResponse = httpclient.execute(build.build())) {
            resultStr = ymsHttpResponse.getBodyString();
            int statusCode = ymsHttpResponse.getStatusCode();
            if (statusCode != HttpStatus.SC_OK) {
                throw new Exception(getHttpInfoStr(statusCode, url, headerParams, bodyParams, resultStr));
            }
        } catch (YmsHttpException e) {
            throw new Exception(getHttpInfoStr(null, url, headerParams, bodyParams, resultStr), e);
        }

        LogUtil.debug("Get请求返回：" + resultStr);
        return StringUtil.cleanXSS(resultStr);
    }


    /**
     * 发送https get请求
     *
     * @param url
     * @return
     * @throws Exception
     * @author lizhgb
     * @Date 2015-9-7 上午9:06:57
     */
    public  String httpsGet(String url) throws Exception {
        return httpsGet(url, null, null);
    }


    /**
     * 发送https get请求
     *
     * @param url
     * @return
     * @throws Exception
     * @author lizhgb
     * @Date 2015-9-7 上午9:06:57
     */
    public  String httpsGet(String url, List<NameValuePair> bodyParams) throws Exception {
        return httpsGet(url, null, bodyParams);
    }


    private  void addHeader(HttpRequestBase request, String name, String value) {
        request.addHeader(StringUtil.htmlEscape(name), StringUtil.htmlEscape(value));
    }


}
